package com.jindouyun.consumer.handle;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.springframework.stereotype.Component;
import java.util.concurrent.Callable;

/**
 * @className: com.jindouyun.consumer.handle.RpcClientHandle
 * @description: Rpc客户端处理器
 * @author: tong.li
 * @createTime: 2021/10/14 14:18
 * @copyright: Tongcheng-Elong Holdings Limited
 */
@Component
public class RpcClientHandle extends SimpleChannelInboundHandler<String> implements Callable {

    private ChannelHandlerContext ctx;

    /** 请求的内容 */
    private String body;

    /** 响应的结果 */
    private String result;


    /**
     * 通道连接就绪事件
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        this.ctx = ctx;
    }

    /**
     * 通道读取就绪事件
     * @param ctx
     * @param msg
     */
    @Override
    protected synchronized void channelRead0(ChannelHandlerContext ctx, String msg) {
        this.result = msg;
        // 将线程唤醒
        notify();
    }



    /**
     * 给服务端异步发送消息
     * @return
     */
    @Override
    public synchronized Object call() throws Exception {
        ctx.writeAndFlush(body);
        // 将线程处于等待状态
        wait();
        return this.result;
    }



    public void setBody(String body) {
        this.body = body;
    }



}
